package com.starblink.store.view

import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.view.animation.AnimationUtils
import android.widget.ImageView
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.postDelayed
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.lifecycleScope
import com.skydoves.balloon.balloon
import com.starblink.android.basic.aroute.CommonRoute
import com.starblink.android.basic.brv.utils.bindingAdapter
import com.starblink.android.basic.brv.utils.models
import com.starblink.android.basic.ext.click
import com.starblink.android.basic.ext.dp
import com.starblink.android.basic.ext.gone
import com.starblink.android.basic.ext.inflater
import com.starblink.android.basic.ext.toast
import com.starblink.android.basic.ext.visible
import com.starblink.android.basic.ext.visibleOrGone
import com.starblink.android.basic.network.base.SkGqlClient
import com.starblink.android.basic.sensorsdata.extension.businessSuffixId
import com.starblink.android.basic.sensorsdata.extension.trackData
import com.starblink.android.basic.sensorsdata.room.entity.SkAntEntity
import com.starblink.android.basic.sensorsdata.spm.GTrackerAssistUtils
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmElementDef
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmPageDef
import com.starblink.android.basic.sensorsdata.spm.impl.SpmTrackHandler
import com.starblink.android.basic.user.UserDataCenter
import com.starblink.android.basic.util.ImageUtils
import com.starblink.android.basic.util.bus.FlowBus
import com.starblink.android.basic.util.bus.FlowConst
import com.starblink.android.basic.util.bus.bean.CollectProductEvent
import com.starblink.android.basic.util.post.CommonMutateManage
import com.starblink.basic.apollo.ext.ApolloValSetExt.apolloValue
import com.starblink.basic.util.CommUtils
import com.starblink.library.widget.balloon.MoreSettingBalloonFactory
import com.starblink.library.widget.balloon.MoreSettingBalloonFactory1
import com.starblink.library.widget.wishlist.WishlistAddBottomDialog
import com.starblink.library.widget.wishlist.bean.BatchProductArrEntry
import com.starblink.rocketreserver.fragment.ProductF
import com.starblink.store.R
import com.starblink.store.StoreManager
import com.starblink.store.databinding.WidgetProductCardHorizontalBinding

/**
 * 水平样式商品卡片View
 */
class ProductCardHorizontalView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleRes: Int = 0,
) : ConstraintLayout(context, attrs, defStyleRes) {
    //===传参数据START
    lateinit var product: ProductF
    lateinit var activity: FragmentActivity
    var position: Int = 0
    var trackPage: Int = 0
    var trackPageForComparePriceDialog: Int = 0
    var searchTerm: String = ""
    var searchResultEmpty: Boolean = false
    //===传参数据END

    // Widget视图
    val binding: WidgetProductCardHorizontalBinding =
        WidgetProductCardHorizontalBinding.inflate(inflater, this)

    init {
        // 使用ViewBinding.inflate方式添加Widget视图，root View的padding等属性会失效
//        setPadding(12.dp, 0, 12.dp, 0)
    }

    // 更多设置弹窗
    private val balloonMoreSetting by binding.root.balloon<MoreSettingBalloonFactory1>()

    /**
     * 横向商品卡片绑定数据
     */
    fun bindProduct(
        activity: FragmentActivity,
        product: ProductF, // 商品对象
        showTopBottomSpace: Boolean = false, // 是否显示顶部间距，底部分割线
        position: Int, // 埋点：列表位置
        trackPage: Int, // 埋点：页面
        trackPageForComparePriceDialog: Int,//埋点：比价弹窗页面
        searchTerm: String = "", // 埋点：搜索关键词
        searchResultEmpty: Boolean = false, // 埋点：搜索结果为空
    ) {
        this.product = product
        this.activity = activity
        this.position = position
        this.trackPage = trackPage
        this.trackPageForComparePriceDialog = trackPageForComparePriceDialog
        this.searchTerm = searchTerm
        this.searchResultEmpty = searchResultEmpty

        // 埋点：横向商品卡片 曝光，点击
        trackData(
            page = trackPage,
            element = SpmElementDef.ProductDetailNewBody,
            traceInfo = product.traceInfo,
            params = trackMap(),
            businessSuffixID = businessSuffixId(product)
        )
        setOnClickListener {
            StoreManager.navigationToProductWebPage(activity, product)
        }

        if(showTopBottomSpace){
//            binding.vTopSpace.visible()
            binding.vBottomDivider.visible()
        }

        //主图
        ImageUtils.loadRoundCircleImage(
            activity,
            product.mainImg ?: "",
            binding.ivProductPic,
            6
        )
        binding.ivProductPic.run {
            trackData(
                page = trackPage,
                element = SpmElementDef.ProductDetailNewBody,
                traceInfo = product.traceInfo,
                params = trackMap(),
                businessSuffixID = businessSuffixId(product),
                onlyHit = true
            )
            setOnClickListener{
                StoreManager.navigationToProductWebPage(activity, product)
            }
        }
        binding.ivProductPic.setOnLongClickListener {
            if (product.mainImg.isNullOrEmpty().not() && product.id.isNullOrEmpty().not()) {
                CommonRoute.toFindSimilarGoods(product.mainImg!!, product.id!!, product.type)

                SpmTrackHandler.addSingleTrackData(
                    SkAntEntity(
                        spmCnt = GTrackerAssistUtils.fetchElementValue(
                            trackPage,
                            SpmElementDef.Element_33043
                        ),
                        traceInfo = product.traceInfo ?: "",
                        params = trackMap()
                    )
                )
            }
            true
        }

        //主图-折扣标签
        binding.tvDiscountTag.visibleOrGone(
            product.disCountInfo?.discountPercent.isNullOrEmpty().not()
        ) {
            text = "-${product.disCountInfo?.discountPercent}"
        }

        // 价格
        binding.tvPrice.visibleOrGone(product.price != null) {
            show(
                product.price!!,
                product.currency,
                product.currencySymbol
            )
            setPriceColor(
                CommUtils.getColor(
                    if (product.disCountInfo?.underlinePrice != null)
                        com.starblink.basic.style.R.color.gu_brand_600
                    else com.starblink.basic.style.R.color.gu_text_primary
                )
            )
        }

        // 折扣价格
        binding.tvPriceOff.visibleOrGone(product.disCountInfo?.underlinePrice != null) {
            show(
                product.disCountInfo?.underlinePrice!!,
                product.currency,
                product.currencySymbol
            )
        }

        // 品牌
        binding.tvBrand.visibleOrGone(product.hotBrand?.name.isNullOrEmpty().not()) {
            text = product.hotBrand?.name
        }

        // 名字
        binding.tvName.text = product.title

        // 更多按钮
        binding.ivMore.setOnClickListener { showMoreSettingPopup(binding.ivMore) }

        // 收藏按钮
        binding.ivCollect.run {
            updateCollect(product.collected)
            click { doCollectProduct() }
        }
        // 事件处理：商品收藏数据
        FlowBus.with<CollectProductEvent>(FlowConst.COLLECT_PRODUCT_EVENT).register(this) { event ->
            if (event.id != null) {
                if (event.id == this.product.id) {
                    this.product.apolloValue("collected", event.collect)
                    updateCollect(this.product.collected)
                }

                product.brotherOffers?.forEach {
                    if (event.id == it?.brotherOfferF?.productId) {
                        it?.brotherOfferF?.run {
                            apolloValue("collected", event.collect)
                        }
                    }
                }
            }
        }

        bindBottomView()
    }

    private fun bindBottomView() {
        // 仅当其他店铺也卖该商品时，显示底部视图
        binding.layoutBottom.visibleOrGone(product.brotherOffers.isNullOrEmpty().not()) {
            binding.logoMerchant1.load(
                product.brotherOffers!![0]?.brotherOfferF?.merchantWeb?.logo ?: "", null
            )
            binding.logoMerchant2.visibleOrGone(product.brotherOffers!!.size >= 2){
                binding.logoMerchant2.load(
                    product.brotherOffers!![1]?.brotherOfferF?.merchantWeb?.logo ?: "", null
                )
            }
            binding.logoMerchant3.visibleOrGone(product.brotherOffers!!.size >= 3){
                binding.logoMerchant3.load(
                    product.brotherOffers!![2]?.brotherOfferF?.merchantWeb?.logo ?: "", null
                )
            }
            binding.tvStoreNum.text = "Sold in ${product.brotherOffers?.size} other stores"
            binding.btnComparePrice.run {
                trackData(
                    page = trackPage,
                    element = SpmElementDef.ProductDetailPriceCheckClick,
                    onlyHit = true,
                    traceInfo = product.traceInfo,
                    params = trackMap()
                )
                click {
                    // 显示店铺商品比价弹窗
                    StoreProductCompareDialog(
                        context = activity,
                        curProduct = product,
                        list = product.brotherOffers,
                        trackPage = trackPageForComparePriceDialog,
                        searchTerm = searchTerm
                    ).show(
                        activity.supportFragmentManager,
                        "StoreProductCompareDialog"
                    )
                }
            }
        }
    }

    /**
     * 收藏商品
     */
    private fun doCollectProduct(fromPopupWindow: Boolean = false) {
        CommonMutateManage.collectProduct(
            ctx = context,
            id = product.id!!,
            type = product.type,
            scope = activity.lifecycleScope,
            collected = (product.collected == true),
            refreshState = {
                updateCollect(product.collected != true)
            }
        ) { it, collected ->
            if (it) {
                // 收藏或取消收藏成功，更新数据
                product.apolloValue("collected", collected)

                // 收藏成功，显示Add To Board提示
                binding.layoutAddToBoard.visibleOrGone(product.collected == true) {
                    this.animation = AnimationUtils.loadAnimation(context, android.R.anim.fade_in)
                        .apply {
                            duration = 500L
                        }
                    this.animation?.start()
                    this.postDelayed(3000L) {
                        this.gone()
                    }
                    this.setOnClickListener {
                        WishlistAddBottomDialog.showAddListDialog(
                            context,
                            batchPros = arrayListOf(
                                BatchProductArrEntry(
                                    id = product.id ?: "",
                                    type = product.type,
                                    url = product.mainImg ?: ""
                                )
                            ),
                            spmPageValue = trackPage
                        )
                    }
                }

                // 埋点
                var element: Int = if (fromPopupWindow) {
                    SpmElementDef.POP_FIND_SIMILAR_ADD
                } else {
                    SpmElementDef.itemCardCollection
                }
                SpmTrackHandler.addSingleTrackData(
                    SkAntEntity(
                        spmCnt = GTrackerAssistUtils.fetchElementValue(
                            trackPage,
                            element
                        ),
                        traceInfo = product.traceInfo ?: "",
                        params = trackMap()
                            .plus("status" to (if (UserDataCenter.isLogin()) "1" else "0"))
                            .plus("result" to if (product.collected == true) "1" else "0")
                    )
                )
            } else {
                // 收藏或取消收藏失败，恢复UI状态
                updateCollect(product.collected)
            }
        }
    }

    private fun showMoreSettingPopup(alignView: View) {
        val balloonView = balloonMoreSetting.getContentView()

        // 找相似
        val vFindSimilar =
            balloonView.findViewById<View>(com.starblink.library.widget.R.id.find_similar)

        vFindSimilar.run {
            trackData(
                page = trackPage,
                element = SpmElementDef.Element_33044,
                onlyHit = true,
                traceInfo = product.traceInfo,
                params = trackMap()
            )

            click {
                if (product.mainImg.isNullOrEmpty() || product.id.isNullOrEmpty()) {
                    toast("data error")
                } else {
                    CommonRoute.toFindSimilarGoods(product.mainImg!!, product.id!!, product.type)
                }
                balloonMoreSetting.dismiss()
            }
        }

        // 收藏
        val vCollect =
            balloonView.findViewById<View>(com.starblink.library.widget.R.id.collect)
        vCollect.visible()
        vCollect.click {
            doCollectProduct(true)
            balloonMoreSetting.dismiss()
        }
        val vCollectTitle =
            balloonView.findViewById<TextView>(com.starblink.library.widget.R.id.collect_title)
        vCollectTitle.text = if (product.collected == true) "Added" else "Add"

        val vCollectImg =
            balloonView.findViewById<ImageView>(com.starblink.library.widget.R.id.collect_img)
        vCollectImg.setImageResource(if (product.collected == true) com.starblink.library.widget.R.drawable.ic_wishlist_product_collected else com.starblink.library.widget.R.drawable.ic_wishlist_product_collect)

        balloonMoreSetting.showAlignBottom(alignView)
    }

    // 更新收藏按钮图标
    private fun updateCollect(collected: Boolean?) {
        binding.ivCollect.setImageResource(
            if (collected == true) R.drawable.ic_product_horizontal_collected
            else R.drawable.ic_product_horizontal_collect
        )
    }

    // 埋点参数map
    private fun trackMap(): Map<String, String> {
        val map: MutableMap<String, String> = SpmTrackHandler.trackProductMap(position, product)
        map.remove("type")
        map["searchTerm"] = "$searchTerm"
        if (searchResultEmpty) {
            map["type"] = "recommend"
        }
        return map
    }
}